<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/9/29
 * Time: 16:24
 */

namespace Home\Controller;
use Home\Model\ChatModel;
use Think\Controller;
use Think\Model;

class ChatController extends BaseController {


    /*
     * 心动
     * @param int $from_beat //心动发起方
     * @param int $to_beat //被心动方
     * return 返回心动的状态信息
     */
    public function heart_beat()
    {
        $model = D('heart');
        $from_beat = I('get.from_beat');
        $to_beat = I('get.to_beat');
        $Beat = new ChatModel();
        $is_beat = $Beat->judge_is_beat($from_beat,$to_beat);
        if(empty($is_beat))
        {
            $res = parent::check_vip($from_beat, 1);
            //判断非会员的心动次数是否超过三次
            if (empty($res)) {
                $result = array(
                    'msg' => 'the user is not vip and beat times is out of 3 times',
                    'error' => 'out of limit times',
                    'statu' => 4,
                );
                echo json_encode($result);
                exit;
            }
        }
        $model1 = D('user');
        $where['id'] = $to_beat;
        $user = $model1->where($where)->field('user')->select();
        $mobile = $user[0]['mobile'];//通过id获取到手机号

        if(empty($from_beat)||empty($to_beat))
        {
            $error = array(
                'error'=>404,
                'msg'=>'the id is not correct!'
            );
            echo json_encode($error);
        }
        $condition = array(
            'frombeat'=>$from_beat,
            'tobeat'=>$to_beat,
        );
        $data = array(
            'frombeat'=>$from_beat,
            'tobeat'=>$to_beat,
            'beatime'=>date('Y-m-d H:i:s',time()),
        );
        $res = $model->where($condition)->select();
        //如果已经心动过，就删除心动状态
        if(!empty($res))
        {
            $model->where($condition)->delete();
            $result = array(
                'msg'=>'cancel heart beat success',
                'statu'=>1,
            );
        }else
        {
            $model->data($data)->add();
            R('sms/send_sms', array($mobile,5));//调用短信下发接口发送心动消息
            $condition1 = array(
                'frombeat'=>$to_beat,
                'tobeat'=>$from_beat,
            );
            $search = $model->where($condition1)->select();
            if(!empty($search))
            {
                $result = array(
                    'msg'=>'add heart beat success',
                    'beat'=>'the two person heart beat each other',
                    'statu'=>3,
                );
            }else{
                $result = array(
                    'msg'=>'add heart beat success',
                    'statu'=>2,
                );
            }
        }
        echo json_encode($result);
    }

    /*
     * 聊天时获取自己的昵称与头像
     * @param int $id //用户的id
     * return json 返回用户的头像和昵称
     */
    public function get_chat_userinfo()
    {
        $model = D('userinfo');
        $id = I('get.id');
        $condition['user_id'] = $id;
        $data = $model->where($condition)->field('header_pic,nickname,user_id')->select();
        echo json_encode($data[0],JSON_UNESCAPED_UNICODE);

    }

    /*
     * 随便看看接口
     * @param int $sex //想要随便看看的性别选项
     * @return json //返回随便看看的信息
     */
    public function casual_look()
    {
        $number = I('get.number');
        if(empty($number))
        {
            $number = rand(1,40);
        }
        $sex = I('get.sex');
        $model = new Model();
        $sql = "select a.id,a.type,a.statu,b.nickname,b.self_introduction,b.height,b.constellation,b.mate_selection,b.header_pic ,b.recommend,
        YEAR(CURDATE()) - YEAR (b.birthday) as Age,d.region_name,e.content as annual_income,f.content as hope_marry_time from
         wl_user a left join wl_userinfo b on a.id=b.user_id  left join wl_region d on b.city=d.id
         left join wl_income e on b.annual_income=e.id left join wl_marry f on b.hope_marry_time=f.id where b.sex=$sex and a.type!=5 and a.type!=4
		 and a.type!=10 limit $number,1";
        $data = $model->query($sql);
        echo json_encode($data,JSON_UNESCAPED_UNICODE);
    }

    /*
     * 判断是否是vip用户
     * @param int $id //用户的id
     * @return json //返回判断结果
     */
    public function judge_vip()
    {
        $id = I('get.id');
        $model = D('user');
        $condition['id'] = $id;
        $res = $model->where($condition)->field('statu')->select();
       echo json_encode($res[0]);
    }

    public function index()
    {
        $userinfo = M('userinfo');
        $usql1 = "update wl_userinfo set recommend=1";
        $gx1['recommend'] = 1;
        $userinfo->where(1)->save($gx1);
        $usql2 = "update wl_userinfo set recommend=2 where sex=1 order by rand() limit 1";
        $gx2['recommend']=2;
        $condition2['sex']=1;
        $userinfo->where($condition2)->order('rand()')->limit(1)->save($gx2);
        $usql3 = "update wl_userinfo set recommend=2 where sex=2 order by rand() limit 1";
        $gx3['recommend']=2;
        $condition3['sex']=2;
        $userinfo->where($condition3)->order('rand()')->limit(1)->save($gx3);
        $fromid = I('get.id');
        $sex = I('get.sex');
        $model = new Model();
        $sql = "select a.id,a.type,a.statu,b.nickname,b.self_introduction,b.height,b.constellation,b.mate_selection,b.header_pic ,b.recommend,
        YEAR(CURDATE()) - YEAR (b.birthday) as Age,d.region_name,e.content as annual_income,f.content as hope_marry_time from
         wl_user a left join wl_userinfo b on a.id=b.user_id left join wl_region d on b.city=d.id
         left join wl_income e on b.annual_income=e.id left join wl_marry f on b.hope_marry_time=f.id  where a.id!=$fromid and b.sex=$sex
        and a.type!=5 and a.type!=4 and a.type!=10 order by b.recommend desc,a.statu desc";
        $data = $model->query($sql);
//        var_dump($data);
        $result = $data;
        //增加心跳次数
        foreach($data as $key=>$value)
        {
            $toid = $data[$key]['id'];
            $bsql = "select * from wl_heart where frombeat=$fromid and tobeat=$toid";
            $res = $model->query($bsql);
            if(!empty($res))
            {
                $result[$key]['is_beat']='1';
            }else  {
                $result[$key]['is_beat']='2';
            }
        }
        foreach($result as $key=>$value)
        {
            $toid = $result[$key]['id'];
            if(!empty($toid))
            {
                $lsql = "select * from wl_blacklist where fromid=$fromid and toid=$toid";
                $lres = $model->query($lsql);
                if(!empty($lres))
                {
                    $this->array_remove($result,$key);
                }
            }
        }
        echo json_encode($result,JSON_UNESCAPED_UNICODE);
    }

    public function index_today()
    {
        $fromid = I('get.id');
        $sex = I('get.sex');
        $model = new Model();
        $sql = "select a.id,a.type,a.statu,b.nickname,b.self_introduction,b.height,b.constellation,b.mate_selection,b.header_pic ,b.recommend,
        YEAR(CURDATE()) - YEAR (b.birthday) as Age,d.region_name,e.content as annual_income,f.content as hope_marry_time from
         wl_user a left join wl_userinfo b on a.id=b.user_id left join wl_region d on b.city=d.id
         left join wl_income e on b.annual_income=e.id left join wl_marry f on b.hope_marry_time=f.id  where a.id!=$fromid and b.sex=$sex and a.type!=5 and a.type!=4
         and date(a.register_time)=curdate() order by b.recommend desc,a.statu desc";
        $data = $model->query($sql);
//        var_dump($data);
        $result = $data;
        //增加心跳次数
        foreach($data as $key=>$value)
        {
            $toid = $data[$key]['id'];
            $bsql = "select * from wl_heart where frombeat=$fromid and tobeat=$toid";
            $res = $model->query($bsql);
            if(!empty($res))
            {
                $result[$key]['is_beat']='1';
            }else  {
                $result[$key]['is_beat']='2';
            }
        }

        foreach($result as $key=>$value)
        {
            $toid = $result[$key]['id'];
            if(!empty($toid))
            {
                $lsql = "select * from wl_blacklist where fromid=$fromid and toid=$toid";
                $lres = $model->query($lsql);
                if(!empty($lres))
                {
                    $this->array_remove($result,$key);
                }
            }
        }
        echo json_encode($result,JSON_UNESCAPED_UNICODE);
    }

    //对数组进行排序与下标重新排列
    function array_remove(&$arr, $offset)
    {
        array_splice($arr, $offset, 1);
    }


/*
 * 按条件进行查询
 * @param int $id //自己的用户id,搜索时要将这个id去掉
 * @param int $type //搜索的类型，1为uid精确搜索，2为模糊条件搜索
 */
    public function search_user()
    {
        $model = new Model();
        $id = I('post.id');
        $sex = I('post.sex');
        $type = I('post.type');//搜索的类型，1为uid搜索，2为条件搜索
        $identify_auth = I('post.auth_type');//身份认证
        $education_auth = I('post.education_auth');//学历认证
        $house_auth = I('post.house_auth');//房产认证
        $car_auth = I('post.car_auth');//车辆认证
        if($type==1)
        {
           $uid = I('post.uid');
            $sql = "select a.id,a.type,a.statu,b.nickname,b.self_introduction,b.height,b.constellation,b.mate_selection,b.header_pic ,b.recommend,
        YEAR(CURDATE()) - YEAR (b.birthday) as Age,d.region_name,e.content as annual_income,f.content as hope_marry_time from
         wl_user a left join wl_userinfo b on a.id=b.user_id left join wl_region c on b.city=c.id left join wl_region d on c.parent_id=d.id
         left join wl_income e on b.annual_income=e.id left join wl_marry f on b.hope_marry_time=f.id where b.uid=$uid";
            $data = $model->query($sql);
            $toid = $data[0]['id'];
            $bsql = "select * from wl_heart where frombeat=$id and tobeat=$toid";
            $res = $model->query($bsql);
            if(!empty($res))
            {
                $data[0]['is_beat'] = 1;
            }else{
                $data[0]['is_beat'] = 2;
            }
        }elseif($type==2)
        {
            //基本筛选
           $start_height = I('post.start_height');
            $end_height = I('post.end_height');
            $start_age = I('post.start_age');
            $end_age = I('post.end_age');
            $annual_income = I('post.annual_income');
            $region = I('post.region');
            $chengshi = $this->select_chengshi_id($region);
            $sql = "select a.id,a.type,a.statu,b.nickname,b.self_introduction,b.height,b.constellation,b.mate_selection,b.header_pic ,b.recommend,
        YEAR(CURDATE()) - YEAR (b.birthday) as age,c.region_name,e.content as annual_income,f.content as hope_marry_time from
         wl_user a left join wl_userinfo b on a.id=b.user_id left join wl_region c on b.city=c.id left join wl_income e on
          b.annual_income=e.id left join wl_marry f on b.hope_marry_time=f.id where 1=1 and b.sex=$sex";
            if(!empty($start_height)&&!empty($end_height))
            {
              $sql.= "  and b.height>=$start_height and b.height<=$end_height";
            }
            if(!empty($start_age)&&!empty($end_age))
            {
                $sql.=" and (YEAR(CURDATE()) - YEAR (b.birthday))>=$start_age and (YEAR(CURDATE()) - YEAR (b.birthday))<=$end_age";
            }
            if(!empty($annual_income))
            {
                $sql.=" and b.annual_income=$annual_income";
            }
            if(!empty($chengshi))
            {
                $sql.=" and b.city=$chengshi";
            }
            if(!empty($identify_auth))
            {
                $sql.=" and a.type=$identify_auth";
            }
            if(!empty($education_auth))
            {
                $sql.=" and b.education_auth=$education_auth";
            }
            if(!empty($house_auth))
            {
                $sql.=" and b.house_auth=$house_auth";
            }
            if(!empty($car_auth))
            {
                $sql.=" and b.car_house=$car_auth";
            }
            $data = $model->query($sql);
            //增加心跳次数
            foreach($data as $key=>$value)
            {
                $toid = $data[$key]['id'];
                $bsql = "select * from wl_heart where frombeat=$id and tobeat=$toid";
                $res = $model->query($bsql);
                if(!empty($res))
                {
                    $data[$key]['is_beat']='1';
                }else{
                    $data[$key]['is_beat']='2';
                }

                $lsql = "select * from wl_blacklist where fromid=$id and toid=$toid";
                $lres = $model->query($lsql);
                if(!empty($lres))
                {
                    unset($data[$key]);
                }
            }
        }
        sort($data);
        echo json_encode($data,JSON_UNESCAPED_UNICODE);
    }

    /*
     * 获取城市名称对应的id
     * @param string $city //城市名称
     * @param int $city_id // 城市id
     * return 返回城市id
     */
    public function select_chengshi_id($city)
    {
        $model = D('region');
        $condition['region_name'] = $city;
        $data = $model->where($condition)->select();
        $city_id = $data[0]['id'];
        return $city_id;
    }

    /*
     * 拉黑
     * @param int $fromid //拉黑人的id
     * @param int $toid //被拉黑人的id
     * @param int $type //根据type来判断拉黑人与被拉黑人的顺序
     */
    public function blacklist()
    {
        $model = D('blacklist');
        $type = I('get.type');
        $fromid = I('get.fromid');
        $toid = I('get.toid');
        if($type==1)
        {
            $condition['fromid'] = $fromid;
            $condition['toid'] = $toid;
            $where = $model->where($condition)->select();
            if(!empty($where))
            {
                $data = array(
                    'statu'=>3,
                    'msg'=>'has aready blaklist'
                );
                echo json_encode($data);
                exit();
            }

            $data = array(
                'fromid' => $fromid,
                'toid' => $toid,
                'time' => date('y-m-d H:i:s', time()),
            );
            $res = $model->data($data)->add();
            if (!empty($res)) {
                $result = array(
                    'statu' => 1,
                    'msg' => 'blacklist success!'
                );
            } else {
                $result = array(
                    'statu' => 2,
                    'msg' => 'blacklist failed!'
                );
            }
        }elseif($type==2)
        {
            $condition['fromid']=$fromid;
            $condition['toid'] =$toid;
            $res = $model->where($condition)->delete();
            if(!empty($res))
            {
                $result = array(
                    'statu'=>3,
                    'msg'=>'cancel blacklist success!'
                );
            }else{
                $result = array(
                    'statu'=>4,
                    'msg'=>'cancel blacklist failed!'
                );
            }
        }
        echo json_encode($result);
    }

    /*
     * 我的拉黑列表
     * @param int $id //用户的id
     * return 通过用户id返回被其拉黑的列表
     */
    public function my_blacklist()
    {
        $model = new Model();
        $id = I('get.id');
        $sql = "select a.time,b.nickname,b.user_id, YEAR(CURDATE()) - YEAR (b.birthday) as age,b.header_pic from wl_blacklist a,wl_userinfo b where a.toid=b.user_id and a.fromid=$id";
        $data = $model->query($sql);
        echo json_encode($data);
    }

    /*
     * 举报
     * @param array $data //举报内容
     * return 返回举报上传结果
     */
    public function report()
    {
        $model = D('report');
        $setting=C('UPLOAD_SITEIMG_QINIU');
        $Upload = new \Think\Upload($setting);
        if(!empty($_FILES['pic'])) {
            $info = $Upload->upload($_FILES);
            $url = $info['pic']['url'];
        }
        $data = I('post.');
        $data['report_pic'] = $url;
        $data['report_time'] = date('y-m-d H:i:s',time());
        $res = $model->data($data)->add();
        if(!empty($res))
        {
            $result = array(
                'msg'=>'report success',
                'statu'=>1
            );
        }else{
            $result = array(
                'msg'=>'report failed',
                'statu'=>2
            );
        }
        echo json_encode($result);
    }

}